import React, { Component } from 'react';
import {
  StyleSheet, View, FlatList, Text, DeviceEventEmitter, Alert,
} from 'react-native';
import { Icon } from 'native-base';
import produce from 'immer';
import Item from './item';
import TaskList from './task-list';
import Tab from '../tab';
import {
  ListFooter, BlankBackground, Loading,
} from '../../../components';
import * as inspectionService from '../../../services/inspection';
import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';

class InspectionList extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
      total: 0,
      index: 0,
      choice: 'inspect',
    };
  }

  componentDidMount() {
    this._onInitRefresh();
    DeviceEventEmitter.addListener('refreshPageEvent', this.refreshPageEvent);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('refreshPageEvent');
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await inspectionService.queryCheckEquipment({ page: currPage });

      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshPageEvent = () => {
    this.index = 0;
    this._onInitRefresh();
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await inspectionService.queryCheckEquipment({ page: 1 });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await inspectionService.queryCheckEquipment({ page: 1 });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
        if (list.length > 0) {
          draft.index = 1;
        } else {
          draft.index = 0;
        }
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ status: 0, title: 1, type: 1 });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ status: 0, title: 1, type: 1 });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ status: 0, title: 1, type: 1 });
    }
  }

  _onItemClick = (item) => {
    // const params = {
    //   fromNavigation: true,
    //   id: item._id,
    //   code: item.failureCode,
    // };
    // // alert(JSON.stringify(params));
    // global.navigation.navigate({ routeName: 'Info', params });

    global.navigation.navigate({
      routeName: 'PollingRecord',
      params: {
        data: item,
      },
    });
  }

  // 列表的item组件
  _renderItem = (item) => (<Item item={item.item} onItemClick={this._onItemClick} />);

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 0.5, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _onScrollStart = (event) => {
    this.startPosition = event.nativeEvent.contentOffset.y;
  }

  _onScrollEnd = (event) => {
    const distance = event.nativeEvent.contentOffset.y - this.startPosition;
    if (distance > 100) {
      if (this._FlatList) {
        if (this.index < this.state.list.length - 1) {
          this.index = this.index + 1;
          this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
        }
      }
    } else if (distance < -100) {
      if (this._FlatList) {
        if (this.index > 0) {
          this.index = this.index - 1;
          this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
        }
      }
    } else {
      this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
    }

    this.setState(produce(draft => {
      draft.index = this.index + 1;
    }));
  }

  change = (_name, showInfo) => {
    // DeviceEventEmitter.emit('changePageIndexEvent', 'devices');
    // eslint-disable-next-line no-unused-expressions
    // this.state.choice === 'all' ? this.setState({ choice: 'todo' }, () => this.refreshPageEvent()) : this.setState({ choice: 'all' }, () => this.refreshPageEvent());
    DeviceEventEmitter.emit('showInfoPageEvent', showInfo);
    this.setState({ choice: _name });
  }

  showTopBar = () => {
    DeviceEventEmitter.emit('showTopBarEvent');
  }

  toQrcode = () => {
    global.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'toInspectTaskDeviceDetail' } });
  }

  toSearch = () => {
    DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
  }

  toAddPageCheck = async () => {
    // global.navigation.navigate({ routeName: 'AddIncident', params: { flag: 'add', sbid: '', sbmc: '', sbbm: '', equipObjType: '', maintOrgId: '', maintOrgName: '' } });
    const { data } = await inspectionService.checkExist({});
    if (data) {
      Alert.alert(
        '提示',
        '当前有未完成的巡检任务,是否继续创建点巡检任务',
        [
          {
            text: '取消',
            style: 'cancel',
          },
          {
            text: '创建',
            onPress: () => {
              this.toAddPage();
            },
          },
        ],
      );
    } else {
      this.toAddPage();
    }
  }

  toAddPage = () => {
    global.navigation.navigate({ routeName: 'CreatTask', params: {} });
  }

  _FlatList;

  render() {
    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            ref={(ref) => {
              this._FlatList = ref;
            }}
            renderItem={this._renderItem}
            data={list}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            decelerationRate={0.1}
            onScrollBeginDrag={this._onScrollStart}
            onScrollEndDrag={this._onScrollEnd}
            scrollEventThrottle={200}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
            // ItemSeparatorComponent={this._renderItemSeparator}
          />
        );
      }
    }
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={{ flex: 1 }}>
            <ZlstIcon
              onPress={this.toSearch}
              name="sousuokuangnei"
              size={22}
              color="white"
              style={{ marginLeft: 20 }}
            />
          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', flex: 1 }}>
            <Text onPress={() => this.change('task', false)} style={[styles.shadow, { fontSize: this.state.choice === 'task' ? 18 : 16, color: this.state.choice === 'task' ? 'white' : 'grey' }]}>任务</Text>
            <Text style={{ color: 'grey', fontSize: 18 }}> | </Text>
            <Text onPress={() => this.change('inspect', true)} style={[styles.shadow, { fontSize: this.state.choice === 'inspect' ? 18 : 16, color: this.state.choice === 'inspect' ? 'white' : 'grey' }]}>巡检</Text>
            <Text style={{ color: 'grey', fontSize: 18 }}> | </Text>
            <Text onPress={() => this.change('mine', false)} style={[styles.shadow, { fontSize: this.state.choice === 'mine' ? 18 : 16, color: this.state.choice === 'mine' ? 'white' : 'grey' }]}>我的</Text>
          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', flex: 1  }}>
            <ZlstIcon
              onPress={this.toQrcode}
              name="saoma"
              size={24}
              color="white"
              style={{ marginRight: 20 }}
            />
            <Icon
              onPress={this.showTopBar}
              type="MaterialCommunityIcons"
              name="dots-horizontal"
              style={{ marginRight: 10, fontSize: 22, color: 'white' }}
            />
          </View>
        </View>
        <Tab toAddPage={this.toAddPageCheck} />
        {this.state.choice === 'inspect' && (
          <View style={styles.float_pagesize}>
            <Text style={{ color: 'white', paddingLeft: 5 }}>
              {this.state.index}/{this.state.total}
            </Text>
          </View>
        )}
        {this.state.choice === 'inspect' && (mView)}
        {this.state.choice === 'task' && (<TaskList title={this.state.choice} />)}
        {this.state.choice === 'mine' && (<TaskList title={this.state.choice} />)}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  shadow: {
    textShadowRadius: 2,
    textShadowColor: 'black',
  },
  container: {
    flex: 1,
    width: '100%',
    backgroundColor: Theme.myPrimary,
  },
  slide: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  header: {
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
    height: 48,
    zIndex: 1,
  },
  icon_container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    color: 'white',
    padding: 10,
  },
  badge: {
    height: 10,
    width: 10,
    backgroundColor: 'red',
    borderRadius: 5,
    marginRight: 5,
  },
  float_pagesize: {
    right: 0,
    top: 60,
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: 'center',
    color: 'white',
    alignItems: 'center',
    borderTopLeftRadius: 11,
    borderBottomLeftRadius: 11,
    backgroundColor: 'rgba(255,255,255,0.30)',
    paddingLeft: 5,
    paddingRight: 5,
    height: 22,
    zIndex: 1,
  },
});

export default InspectionList;
